<template>
  <div class="captcha-container" @click="refreshCaptcha" v-loading="loading">
    <div v-if="captchaSvg" v-html="captchaSvg" class="captcha-svg"></div>
    <div v-else class="captcha-placeholder">点击获取验证码</div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '../api/request'

const props = defineProps({
  width: {
    type: Number,
    default: 120
  },
  height: {
    type: Number,
    default: 40
  }
})

const captchaSvg = ref('')
const loading = ref(false)

// 获取验证码
const fetchCaptcha = async () => {
  loading.value = true
  try {
    const response = await request({
      url: '/api/captcha',
      method: 'get',
      responseType: 'text' // 获取文本格式的 SVG
    })
    captchaSvg.value = response
  } catch (error) {
    console.error('获取验证码失败:', error)
    captchaSvg.value =
      '<svg><text x="10" y="25" fill="red">获取失败</text></svg>'
  } finally {
    loading.value = false
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  fetchCaptcha()
}

// 暴露方法给父组件
defineExpose({
  refreshCaptcha
})

onMounted(() => {
  fetchCaptcha()
})
</script>

<style scoped>
.captcha-container {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
  width: 120px;
  height: 40px;
  background: #f0f0f0;
}

.captcha-container:hover {
  border-color: #06b6d4;
  box-shadow: 0 0 8px rgba(6, 182, 212, 0.3);
}

.captcha-svg {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.captcha-svg :deep(svg) {
  width: 100%;
  height: 100%;
}

.captcha-placeholder {
  font-size: 12px;
  color: #999;
  text-align: center;
}
</style>
